package demo.components.kafka;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;
import kafka.serializer.StringDecoder;
import kafka.utils.VerifiableProperties;

import org.apache.log4j.Logger;

public class KafkaConsumer {
    private static final Logger logger = Logger.getLogger(KafkaConsumer.class);
    private final ConsumerConnector consumer;
    private final Properties props = new Properties();

    public KafkaConsumer(String groupId, String brokers) {
        props.put("zookeeper.connect", brokers);
        props.put("group.id", groupId);

        props.put("refresh.leader.backoff.ms", "400");
        props.put("zookeeper.session.timeout.ms", "30000");
        props.put("rebalance.max.retries", "10");
        props.put("rebalance.backoff.ms", "4000");
        // autoCommit
        props.put("auto.commit.enable", "true");
        props.put("auto.commit.interval.ms", "2000");
        props.put("auto.offset.reset", "largest");
        props.put("partition.assignment.strategy", "range");
        props.put("serializer.class", "kafka.serializer.StringEncoder");
        props.put("fetch.wait.max.ms", "200");
        props.put("fetch.message.max.bytes", "2097152");
        ConsumerConfig config = new ConsumerConfig(props);
        this.consumer = Consumer.createJavaConsumerConnector(config);
    }

    public void consume(String topic, KafkaMessageHandler handler) {
        Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
        topicCountMap.put(topic, 1);
        StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());
        StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());
        Map<String, List<KafkaStream<String, String>>> consumerMap = this.consumer.createMessageStreams(topicCountMap,
                keyDecoder, valueDecoder);
        List<KafkaStream<String, String>> streamList = consumerMap.get(topic);
        ConsumerIterator<String, String> it = streamList.get(0).iterator();
        while (it.hasNext()) {
            MessageAndMetadata<String, String> message = it.next();
            try {
                handler.processMessage(this, message.message(), message.offset());
            } catch (Exception e) {
                logger.error("Process message failed", e);
            }
        }
        // } catch (Exception e) {
        // logger.error("kafkaConsumer exeption: " + e);
        // }
    }

    public void commit() {
        if (this.consumer != null) {
            this.consumer.commitOffsets(true);
        }
    }

    public void shutdown() {
        if (this.consumer != null) {
            this.consumer.shutdown();
        }
    }

}
